<template>
  <el-card class="index-container">
    <template #header>
      <div class="header">
        <div class="search-container">
          <el-input
              v-model="state.searchValue"
              placeholder="养老院名称关键字"
              clearable
              style="width: 300px; margin-right: 10px"
          />
          <el-button type="success" color="#71c4ef" @click="handleSearch">查询</el-button>
          <el-button type="success" color="#313d44" plain @click="handleReset">重置</el-button>
        </div>
        <div class="action-buttons">
          <el-button type="primary" color="#FF3D3D" :icon="Plus" @click="handleAdd">增加</el-button>
          <el-popconfirm
              title="确定要批量删除吗？"
              confirm-button-text="确认"
              cancel-button-text="取消"
              @confirm="AllDetele"
          >
            <template #reference>
              <el-button type="primary" color="red" size="size" style="margin-left: 8px">
                批量删除
              </el-button>
            </template>
          </el-popconfirm>
        </div>
      </div>
    </template>

    <el-table
        :load="state.loading"
        ref="multipleTable"
        :data="state.tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="序号"
          align="center"
          width="120"
      >
        <template #default="scope">
          {{ (state.currentPage - 1) * state.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
          prop="name"
          label="名称"
          align="center"
      >
      </el-table-column>

      <el-table-column
          label="图片"
          align="center"
          width="120"
      >
        <template #default="scope">
          <img :src="scope.row.image" alt="图片" style="width: 80px; border-radius:12px; height: 80px; object-fit: cover;">
        </template>
      </el-table-column>

      <el-table-column
          prop="price"
          label="价格"
          align="center"
      >
      </el-table-column>

      <el-table-column
          prop="address"
          label="地址"
          align="center"
      ></el-table-column>

      <el-table-column
          prop="tags"
          label="标签"
          align="center"
      ></el-table-column>

      <el-table-column
          prop="beds"
          label="床位"
          align="center"
      ></el-table-column>

      <el-table-column
          prop="nature"
          label="性质"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="type"
          label="类型"
          align="center"
      ></el-table-column>


      <el-table-column label="内容" align="center" width="150" prop="content">
        <template #default="scope">
          <el-button type="warning" size="small" @click="ShowContent(scope.row.content)">
            查看内容
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <div class="action-buttons">
            <!-- 编辑按钮 -->
            <el-button
                type="warning"
                size="small"
                :icon="Edit"
                :disabled="scope.row.id === '1'"
                @click="handleEdit(scope.row.id)">
              编辑
            </el-button>

            <!-- 删除按钮（带确认） -->
            <el-popconfirm
                title="确定要删除此项吗？"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="handleDeleteOne(scope.row.id)"
            >
              <template #reference>
                <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    :disabled="scope.row.id === '1'"
                    style="margin-left: 8px">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--总数超过一页，再展示分页器-->
    <el-pagination
        v-if="state.total > state.pageSize"
        background
        layout="prev, pager, next"
        :total="state.total"
        :page-size="state.pageSize"
        :current-page="state.currentPage"
        @@size-change="handleSizeChange"
        @current-change="changePage"
    />
  </el-card>

  <el-dialog title="内容" v-model="fromVisible" width="50%">
    <div>
      <div v-html="state.content"></div>
    </div>
    <div slot="footer" class="dialog-footer">
        <span>
          <el-button style="float: right" type="primary" @click="fromVisible =false">确 定</el-button>
        </span>
    </div>
  </el-dialog>


  <!--  编辑弹窗控件-->
  <NursingHomeDialog ref='infoClassify' :reload="getIndexConfig" :type=state.type
                     :configType="state.configType"/>
</template>




<script setup>
import {onMounted, reactive, ref, toRefs} from 'vue'
import {ElMessage} from 'element-plus'
import NursingHomeDialog from '../../components/NursingHomeDialog.vue'
import {useRoute, useRouter} from 'vue-router'
import {Check, Delete, Edit, Message, Search, Star,} from '@element-plus/icons-vue'
import {fileUpload} from '../../service/minioFileApi.js'
import {getNursingHomeById, deleteNursingHomeById, listNursingHomes , batchDeleteNursingHome} from '../../service/nursingHomeApi.js'

// 首页配置类型参数
const configTypeMap = {
  hot: 3,
  new: 4,
  recommend: 5
}

const ShowContent = (content) => {
  fromVisible.value = true
  state.content = content

}
const fromVisible = ref(false)
const router = useRouter()
const route = useRoute()
const multipleTable = ref(null)
const infoClassify = ref(null)
const state = reactive({
  editor:null,
  searchValue: '', // 新增搜索值
  loading: false,
  tableData: [], // 数据列表
  multipleSelection: [], // 选中项
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  type: 'add', // 操作类型
  configType: 3, // 3-(首页)热销商品 4-(首页)新品上线 5-(首页)为你推荐
  content:''
})


const show = () => {
  // 富文本编辑器实例创建

  state.editor = new E('#editor')
  //配置上传地址
  state.editor.config.customUploadImg = async function (resultFiles, insertImgFn) {
    const response = await fileUpload(resultFiles[0]);
    insertImgFn(response.data)
  }
  state.editor.config.menus = [
    // 菜单配置
    'head', // 标题
    'bold', // 粗体
    'italic', // 斜体
    'underline', // 下划线
    'link', // 插入链接
    'image', // 插入图片
    'undo', // 撤销
    'redo' // 重复
  ]
  state.editor.create()

}
// 监听路由变化
router.beforeEach((to) => {
  if (['hot', 'new', 'recommend'].includes(to.name)) {
    state.configType = configTypeMap[to.name]
    state.currentPage = 1
    getIndexConfig()
  }
})

// 初始化
onMounted(() => {
  state.configType = configTypeMap[route.name]
  getIndexConfig()
})

// 获取列表数据（添加搜索参数）
const getIndexConfig = async () => {
  state.loading = true
  const params = {
    pageNum: state.currentPage,
    pageSize: state.pageSize,
    keyWord: state.searchValue
  }
  // 查询资讯分类列表数据
  const response = await listNursingHomes(params);
  state.tableData = response.data.records || []
  state.total = response.data.total || 0
}

// 搜索处理
const handleSearch = () => {
  state.currentPage = 1
  getIndexConfig()
}

// 重置处理
const handleReset = () => {
  state.searchValue = ''
  getIndexConfig()
}

// 其他原有方法保持不变...
// 添加商品
  const handleAdd = () => {
    state.type = 'add'
    infoClassify.value.open()
  }
// 修改商品
  const handleEdit = (id) => {
    console.log('handleEdit', id)
    state.type = 'edit'
    infoClassify.value.open(id)
  }

// 选择项
  const handleSelectionChange = (val) => {
    state.multipleSelection = val
    // state.multipleSelection.map(item => item.id)
  }

// 单个删除
  const handleDeleteOne = (id) => {
    // 原有删除逻辑...
    deleteNursingHomeById(id).then(() => {
      ElMessage.success('删除成功')
      getIndexConfig()
    })
  }

// 分页处理
  const changePage = (val) => {
    state.currentPage = val
    getIndexConfig()
  }

// 每页条数变化
  const handleSizeChange = (val) => {
    state.pageSize = val
    state.currentPage = 1
    getIndexConfig()
  }

// 批量删除
const AllDetele = async  () => {
  if (!state.multipleSelection.length) {
    ElMessage.error('请选择项')
    return
  }
  const response = await batchDeleteNursingHome(state.multipleSelection.map(item => item.id));
  if (response.code === 200) {
    ElMessage.success('删除成功')
    await getIndexConfig()
  } else {
    ElMessage.error('删除失败')
  }
}
</script>

<style scoped>
.index-container {
  min-height: 100%;
}

.el-card.is-always-shadow {
  min-height: 100% !important;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  flex: 1;
  margin-right: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end; /* 将内容推到容器末尾 */
  align-items: center; /* 垂直居中 */
}
</style>
